
$(function(){
    let _deleteIds = null, _action = '/add',_row = null;
    const convertor = {type:[]};
    const alerter = Frame2.alert.init({$div:$('#alertbar')});
    const setting = {
        check: {
            enable: true,
            chkboxType: { "Y": "p", "N": "p" }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
            }
        }
    };
    function loadTree(reload) {
        $.ajax({
            url: _PATH + '/web/system/auth/permission/getAllPermissionTree',
            type: 'POST',
            dataType: 'json',
            data: {},
            success: function (result) {
                openTree(result.data);
                $.fn.zTree.init($("#permissiontree"), setting, result.data);
            }, complete: function () {
                let zTree = $.fn.zTree.getZTreeObj("permissiontree");
            }
        });
    }
    function openTree(tree) {
        if(tree == null) return;
        tree.open = true;
        if (tree.children.length == 0) {
            delete tree.children;
            return;
        }
        for(let i=0; i<tree.children.length; i++) {
            openTree(tree.children[i]);
        }
    }
    const table = $('#table').bootstrapTable({
        url: _DIR + '/table',
        method: 'POST',
        toolbar:'#formbar',
        pagination: true,
        sidePagination: 'server',//服务器端分页 返回数据 {rows:[],total:1}
        pageNumber: 1,
        pageSize: 15,
        pageList: [15, 20, 50, 100],//分页步进值
        columns: [{checkbox: true, valign: "bottom"},
        {
            showSelectTitle:true,
            field: 'id',
            title: 'ID',sortable:true
        }, {
            field: 'pid',
            title: 'PID',
        }, {
            field: 'name',
            title: '角色名'
        }, {
            field: 'shiro',
            title: '权限码'
        }, {
            field: 'permisions',
            title: '拥有权限',
            formatter: (value, row, index, field) => {
                let len = row.permissions.length;
                return len==0?'暂无':(len + '个')
            }
        },{
            field: 'description',
            title: '备注'
        }, {
            title:'操作',
            align: 'center',
            class: 'action',
            formatter: (value, row, index, field) => {
                let btn = '<button type="button" class="btn btn-xs btn-success view" title="点击查看资源详情">查看</button>';
                if (row.id == 1) {
                    btn += '<button type="button" class="btn btn-xs" disabled>系统管理员禁止修改和删除</button>';
                } else {
                    btn += '<button type="button" class="btn btn-xs btn-primary update">修改</button>'
                        +'<button type="button" class="btn btn-xs btn-warning permission">设置权限</button>'
                        +'<button type="button" class="btn btn-xs btn-danger del">删除</button>';
                }
                return btn;
            },
            events:{
                'click .view': function(e,value,row,index){
                    let view = $('#viewModal');
                    view.find("#view_name").text(row.name);
                    view.find("#view_shiro").text(row.shiro);
                    view.find('#view_createTime').text(new Date(row.createTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                    view.find('#view_updateTime').text(new Date(row.updateTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                    view.find("#view_description").text(row.description);
                    let perms = null;
                    if (row.permissions.length) {
                        perms = [];
                        $.each(row.permissions, (i,v) => {perms.push(v.name)})
                        perms = perms.join('； ');
                    } else {
                        perms = '暂无任何权限'
                    }
                    view.find("#view_permissions").text(perms);
                    view.modal('show');
                },
                'click .update': function(e,value,row,index) {
                    let form = $('#addForm'),modal = $('#addModal');
                    _action = '/update';
                    modal.find('.modal-title').text('修改角色信息');
                    form.find("[name='id']").val(row.id);
                    form.find("[name='name']").val(row.name);
                    form.find("[name='shiro']").val(row.shiro);
                    form.find("[name='description']").val(row.description);

                    modal.modal('show');
                    form.data('bootstrapValidator').resetForm();
                    //alert(form.data('bootstrapValidator').isValid())
                },
                'click .permission': function (e,value,row,index) {
                    let form = $('#permissionForm'),modal = $('#permissionModal');
                    _row = row;
                    let treeObj = $.fn.zTree.getZTreeObj("permissiontree");
                    treeObj.checkAllNodes(false);
                    let node=null;
                    for (let i=0; i< row.permissions.length; i++) {
                        node = treeObj.getNodeByParam('id',row.permissions[i].id);
                        if (node != null) // 选中已有的权限
                            treeObj.checkNode(node, true, true);
                    }
                    modal.modal('show');
                },
                'click .del': function(e,value,row,index){
                    _deleteIds = [row.id];
                    $('#deleteModal').modal('show');
                },
            }
        }],
        queryParams:function(params) {
            let $array = $('#formbar').serializeArray();
            $.each($array, function(index, val) {
                if(val.value && val.value.trim())
                    params[val.name]=val.value.trim();
            });
            return params;
        },
    });

    $('#listbar').on('click', '.add', function(event) {
        event.preventDefault();
        let form = $('#addForm'),modal = $('#addModal');
        form.find("[name='id']").val(0);
        _action = '/add';
        modal.find('.modal-title').text('创建新角色');
        modal.modal('show');
    });
    $('#listbar').on('click', '.del', function(event) {
        event.preventDefault();
        _deleteIds = Frame2.bootstrap.getSelectionsAttr(table,'id');
        if (_deleteIds == null || _deleteIds.length == 0) {
            alerter.show(100,function(){},{autohide:3000,title:'提示：',content:'请选择要删除的数据！'})
        } else{
            $('#deleteModal').modal('show');
        };
    });
    //确认删除事件
    $('#deleteModal').on('click', '.del', function(event) {
        event.preventDefault();
        console.log(_deleteIds)
        $.ajax({
            url: _DIR + '/delete',
            type: 'POST',
            dataType: 'json',
            traditional:true,
            data: {ids: _deleteIds},
            success: function(result) {
                $('#deleteModal').modal('hide');
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'数据删除成功。'})
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            },complete: function(){
                _deleteIds = [];
            }
        });
    });
    //新增表单验证+提交
    $('#addForm').bootstrapValidator(Frame2.bootstrap.validatorConfig({
        fields:{
            username: {
                message: '角色名不合法',//默认提示信息
                validators: {
                    notEmpty: {
                        message: '角色名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 10,
                        message: '角色名必须是2-10个字符'
                    }
                }
            }
        }
    })).on('success.form.bv', function(e) {
        e.preventDefault();
        let form = $(e.target);
        $.ajax({
            url: _DIR + _action,
            type: 'POST',
            dataType: 'json',
            data: form.serialize(),
            success: function(result) {
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'操作成功。'})
                    $('#addModal').modal('hide');
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            }
        });
        return false;
    });
    //确认设置权限
    $('#permissionModal').on('click', '.btn-warning', function(event) {
        event.preventDefault();
        let model = $('#permissionModal');
        let _data = {
            rid: _row.id,
            pids: []
        }
        let treeObj = $.fn.zTree.getZTreeObj("permissiontree");
        let nodes = treeObj.getCheckedNodes();
        for (let i=0; i< nodes.length; i++) {
            _data.pids.push(nodes[i].id)
        }
        $.ajax({
            url: _DIR + '/permission',
            type: 'POST',
            dataType: 'json',
            traditional:true,
            data: _data,
            success: function(result) {
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'角色授权成功。'})
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            },complete: function(){
                model.modal('hide');
                _row = null;
            }
        });
    });
    loadTree(0);
});
